package com.example.springdemo03.service;
import com.example.springdemo03.po.DataModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Slf4j
@Service
@EnableScheduling
public class DealDataService implements InitializingBean {

    public static Resource dataResource;

    @Scheduled(cron = "0 0 1 * * *")
    @Override
    public void afterPropertiesSet(){
        RequestEntity<Void> requestEntity =
                RequestEntity.get(URI.create("https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv"))
                        .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0"))
                        .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        dataResource =  exchange.getBody();
        log.info("确保应用程序启动时，获取一次统计数据。");
    }

    public List<DataModel> getData(){
        BufferedReader bufferedReader = null;
        List<DataModel> virusDataList = new ArrayList<>();
        try {
            InputStream inputStream = dataResource.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);

            Iterable<CSVRecord> records = CSVFormat.DEFAULT.withHeader("Province/State", "Country/Region", "Lat", "Long").parse(bufferedReader);
            Iterator<CSVRecord> iterator = records.iterator();
            iterator.next();
            while (iterator.hasNext()) {
                CSVRecord record = iterator.next();
                DataModel dataModel = new DataModel(
                        record.get("Province/State"),
                        record.get("Country/Region"),
                        Integer.parseInt(record.get(record.size() - 1)),
                        Integer.parseInt(record.get(record.size() - 1)) - Integer.parseInt(record.get(record.size() - 2))
                );
                virusDataList.add(dataModel);
            }
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return virusDataList;
    }

}
